package com.ruoyi.livedemo.controller;

import com.ruoyi.livedemo.common.ApiResponse;
import com.ruoyi.livedemo.dto.AuthLoginRequest;
import com.ruoyi.livedemo.dto.AuthRegisterRequest;
import com.ruoyi.livedemo.dto.LoginResponse;
import com.ruoyi.livedemo.dto.UserProfileView;
import com.ruoyi.livedemo.entity.User;
import com.ruoyi.livedemo.service.AuthService;
import com.ruoyi.livedemo.service.ProfileService;
import com.ruoyi.livedemo.service.TokenService;
import java.time.Duration;
import java.util.Arrays;
import java.util.Optional;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/auth")
// 认证与会话控制器：负责登录、注册、退出以及获取当前登录者信息
public class AuthController {

    private final AuthService authService;
    private final TokenService tokenService;
    private final ProfileService profileService;

    @PostMapping("/register")
    public ApiResponse<User> register(@Valid @RequestBody AuthRegisterRequest request) {
        User user = authService.register(request);
        return ApiResponse.ok("注册成功", user);
    }

    @PostMapping("/login")
    public ResponseEntity<ApiResponse<LoginResponse>> login(@Valid @RequestBody AuthLoginRequest request,
                                                            HttpServletRequest httpRequest,
                                                            HttpServletResponse response) {
        String userAgent = httpRequest.getHeader("User-Agent");
        LoginResponse login = authService.login(request, userAgent);
        ResponseCookie cookie = ResponseCookie.from("AUTH_TOKEN", login.getToken())
                .httpOnly(true)
                .path("/")
                .maxAge(Duration.ofHours(tokenService.getExpireHours()))
                .build();
        response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString());
        return ResponseEntity.ok(ApiResponse.ok("登录成功", login));
    }

    @PostMapping("/logout")
    public ApiResponse<Void> logout(HttpServletRequest request, HttpServletResponse response) {
        String token = resolveToken(request);
        authService.logout(token);
        ResponseCookie cookie = ResponseCookie.from("AUTH_TOKEN", "")
                .path("/")
                .maxAge(0)
                .build();
        response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString());
        return ApiResponse.ok("退出成功", null);
    }

    @GetMapping("/me")
    public ApiResponse<LoginResponse> me(HttpServletRequest request) {
        String token = resolveToken(request);
        if (token == null) {
            return ApiResponse.fail("未登录");
        }
        User user = tokenService.validateToken(token);
        if (user == null) {
            return ApiResponse.fail("登录已过期");
        }
        UserProfileView profile = profileService.loadProfile(user.getId());
        LoginResponse response = new LoginResponse(token, user, profile);
        return ApiResponse.ok(response);
    }

    private String resolveToken(HttpServletRequest request) {
        String header = request.getHeader("Authorization");
        if (header != null && header.startsWith("Bearer ")) {
            return header.substring(7);
        }
        String tokenHeader = request.getHeader("X-Auth-Token");
        if (tokenHeader != null && !tokenHeader.trim().isEmpty()) {
            return tokenHeader;
        }
        if (request.getCookies() != null) {
            Optional<Cookie> cookie = Arrays.stream(request.getCookies())
                    .filter(c -> "AUTH_TOKEN".equals(c.getName()))
                    .findFirst();
            if (cookie.isPresent()) {
                return cookie.get().getValue();
            }
        }
        return request.getParameter("token");
    }
}
